package com.zy.springboot.com;
import com.zy.springboot.DemoApplication;
import org.springframework.util.ResourceUtils;

import javax.servlet.http.HttpServletResponse;
import java.io.*;

/**
 * Created by y on 2019/5/28.
 */
public class downloadUtil {
    private HttpServletResponse response;
    //构造方法，传入要导出的数据
    public downloadUtil(HttpServletResponse response) {
        this.response = response;
    }
    public  void downFile (String fileName){
        if (fileName != null) {
            //设置文件路径
            String realPath = "/usr/local"+"/images/玄幻奇幻/";
            //String realPath = "D://bookSearch//src//main//resources//";
            File file = new File(realPath , fileName);
            //File file = new File( "http://129.211.82.198:8080/山神.txt");
            System.out.println(file);
            System.out.println(file.exists());
            if (file.exists()) {
                response.setContentType("application/force-download");// 设置强制下载不打开
                response.addHeader("Content-Disposition", "attachment;fileName=" + "仙逆.txt");// 设置文件名
                byte[] buffer = new byte[1024];
                FileInputStream fis = null;
                BufferedInputStream bis = null;
                try {
                    fis = new FileInputStream(file);
                    bis = new BufferedInputStream(fis);
                    OutputStream os = response.getOutputStream();
                    int i = bis.read(buffer);
                    while (i != -1) {
                        os.write(buffer, 0, i);
                        i = bis.read(buffer);
                    }
                    System.out.println("success");
                } catch (Exception e) {
                    e.printStackTrace();
                } finally {
                    if (bis != null) {
                        try {
                            bis.close();
                        } catch (IOException e) {
                            e.printStackTrace();
                        }
                    }
                    if (fis != null) {
                        try {
                            fis.close();
                        } catch (IOException e) {
                            e.printStackTrace();
                        }
                    }
                }
            }
        }
     }
    public static String getPath()
    {
        String path = DemoApplication.class.getProtectionDomain().getCodeSource().getLocation().getPath();
        if(System.getProperty("os.name").contains("dows"))
        {
            path = path.substring(1,path.length());
        }
        if(path.contains("jar"))
        {
            path = path.substring(0,path.lastIndexOf("."));
            return path.substring(0,path.lastIndexOf("/"));
        }
        return path.replace("target/classes/", "");
    }
}
